package com.saver.view.item;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.saver.R;
import com.saver.core.util.CommonUtil;
import com.saver.core.util.Constantes;
import com.saver.core.util.DateUtil;
import com.saver.core.util.ItemUtil;
import com.saver.view.MainActivity;
import com.saver.view.adapter.PieListCategoriaAdapter;
import com.saver.view.adapter.PieListCategoriaAdapter.ViewHolder;
import com.saver.view.data.ChartDataUtil;
import com.saver.view.formatter.PercentValueFormatter;
import com.saver.view.gui.FragmentSupport;
import com.saver.view.model.FragmentModel;

import java.util.ArrayList;
import java.util.List;

public class PieChartFragment extends ChartItemFragment implements OnItemClickListener {

    Typeface typeface;
    PieChart chart;
    ListView listView;
    double gastoTotal = 0;
    List<ItemUtil> listaTotales = null;
    private ChartDataUtil chartDataUtil = new ChartDataUtil();

    public static PieChartFragment instanceOf(Bundle args) {
        PieChartFragment fragment = new PieChartFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        typeface = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");
        View view = inflater.inflate(R.layout.fragment_list_item_piechart, container, false);
        //se carga la lista de transacciones
        mChartData = generateDataPie();
        mChartData.setValueTextSize(11f);
        chart = (PieChart) view.findViewById(R.id.piechart);

        chart.setHoleColorTransparent(true);
        chart.setCenterTextColor(Color.BLACK);
        chart.setDescription("");
        chart.setHoleRadius(60f);
        chart.setTransparentCircleRadius(65f);
        chart.setCenterText("Gasto\n" + CommonUtil.formatCurrency(gastoTotal));
        chart.setCenterTextTypeface(typeface);
        chart.setCenterTextSize(20f);
        chart.setRotationEnabled(false);
        chart.setRotationAngle(0);
        chart.setDrawSliceText(false);
        chart.setUsePercentValues(true);
        chart.setData((PieData) mChartData);
        chart.setTouchEnabled(false);
        Legend legend = chart.getLegend();
        legend.setEnabled(false);
        chart.animateXY(1500, 1500);

        PieListCategoriaAdapter adapter = new PieListCategoriaAdapter(getActivity().getBaseContext(), chartDataUtil.generateDataList(listaTotales));
        listView = (ListView) view.findViewById(R.id.listViewDetail);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        return view;
    }

    private PieData generateDataPie() {
        yVals = new ArrayList<Entry>();
        xVals = new ArrayList<String>();
        FragmentModel model = (FragmentModel) getArguments().getSerializable("args");
        listaTotales = chartDataUtil.generateDataPie(model, getActivity());
        int i = 0;
        gastoTotal = 0;
        for (ItemUtil transaccion : listaTotales) {
            if (transaccion.getValor() > 0) {
                yVals.add(new Entry(Float.parseFloat(transaccion.getValor() + "f"), i, transaccion));
                xVals.add(transaccion.getDescripcion());
                i++;
                gastoTotal += Float.parseFloat(transaccion.getValor() + "f");
            }
        }
        PieDataSet dataSet = new PieDataSet(yVals, "");
        dataSet.setColors(chartDataUtil.generateColors(listaTotales));
        if (listaTotales.size() > 1) {
            dataSet.setSliceSpace(2f);
        } else {
            dataSet.setSliceSpace(0f);
        }

        PieData pieData = new PieData(xVals, dataSet);
        pieData.setValueFormatter(new PercentValueFormatter());
        return pieData;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d("item", "lista detalle");
        ViewHolder holder = (ViewHolder) view.getTag();
        if (holder.value.equals(0f)) {
            Toast.makeText(getActivity(), "No tiene gastos en la categoría seleccionada", Toast.LENGTH_SHORT).show();
        } else {
            FragmentModel currentModel = (FragmentModel) getArguments().getSerializable("args");
            FragmentModel model = new FragmentModel();
            model.setTipoGrafico(Constantes.TIPO_GRAFICO_LIST);
            model.setCategoria(holder.id);
            model.setCalendar(currentModel.getCalendar());
            model.setTipoConsulta(currentModel.getTipoConsulta());
            model.setReferencia(DateUtil.FORMATO_GENERAL.format(currentModel.getCalendar().getTime()));
            Bundle bundle = new Bundle();
            bundle.putSerializable("args", model);
            FragmentSupport fragment = new ParentViewPagerFragment();
            fragment.setFragmentName("FRAGMENTO_REGISTRO");
            fragment.setPosition(1);
            fragment.setArguments(bundle);
            MainActivity.main().reemplazarFragmento(fragment);
        }
    }
}
